#include "seg_msgbox.h"
#include "styles.h"
#include "components\lvgl\lvgl.h"

typedef enum _msg_box_status
{
    MSG_BOX_ST_NOT_SHOW,    // 未显示
    MSG_BOX_ST_NM_SHOW,     // 常规显示
    MSG_BOX_ST_TIMER_SHOW   // 定时显示
}msg_box_status_t;

///////////////////// VARIABLES ////////////////////
// 静态定义屏幕内的控件句柄，也可以局部定义。

static lv_obj_t * mMsgBox;
static lv_obj_t * mLable;
static lv_timer_t * mTimer;     // LVGL的软定时器

static msg_box_status_t mStatus = MSG_BOX_ST_NOT_SHOW;

///////////////////// TEST LVGL SETTINGS ////////////////////
//#if LV_COLOR_DEPTH != 16
//    #error "LV_COLOR_DEPTH should be 16bit to match SquareLine Studio's settings"
//#endif
//#if LV_COLOR_16_SWAP !=1
//    #error "LV_COLOR_16_SWAP should be 1 to match SquareLine Studio's settings"
//#endif

///////////////////// ANIMATIONS ////////////////////

///////////////////// FUNCTIONS ////////////////////
static void MsgBox_CreatBase(const char *str)
{
    // 创建并设置面板（和屏幕类似）
    mMsgBox = lv_obj_create(lv_scr_act());    // 消息框建立在当前屏幕下，避免未关闭消息框而删除屏幕导致的内存泄漏
    lv_obj_set_width(mMsgBox, 140);
    lv_obj_set_height(mMsgBox, 50);
    lv_obj_set_align(mMsgBox, LV_ALIGN_CENTER);
    lv_obj_add_style(mMsgBox, &Style_StatusBar, LV_PART_MAIN | LV_STATE_DEFAULT);

    mLable = lv_label_create(mMsgBox);
    lv_obj_set_width(mLable, LV_SIZE_CONTENT);   /// 1
    lv_obj_set_height(mLable, LV_SIZE_CONTENT);    /// 1
    lv_obj_set_align(mLable, LV_ALIGN_CENTER);
    lv_label_set_text(mLable, str);
}

// 当 MsgBox 显示时间到后被调用一次
static void Timer(lv_timer_t * timer)
{
    MsgBox_Close();
}

///////////////////// SEGMENT /////////////////////



void MsgBox_Show(const char *str)
{
    if(mStatus == MSG_BOX_ST_NOT_SHOW)    // 只允许显示1个消息框
    {
        MsgBox_CreatBase(str);
    }
    else if(mStatus == MSG_BOX_ST_NM_SHOW)  // 更改MSGBOX显示内容
    {
        lv_label_set_text(mLable, str);
    }
    else if(mStatus == MSG_BOX_ST_TIMER_SHOW)   // 更改MSGBOX显示内容和去除显示时间计时
    {
        lv_timer_del(mTimer);
        lv_label_set_text(mLable, str);
    }
    mStatus = MSG_BOX_ST_NM_SHOW;
}

void MsgBox_TimerShow(const char *str, int sec)
{
    if(mStatus == MSG_BOX_ST_NOT_SHOW)  // 创建MSGBOX
    {
        mTimer = lv_timer_create(Timer, sec * 1000,  NULL);
        lv_timer_set_repeat_count(mTimer, 1); // 计时器仅重复1次，后会自动被删除
        MsgBox_CreatBase(str);
    }
    else if(mStatus == MSG_BOX_ST_NM_SHOW)  // 更改MSGBOX显示内容和设置显示时间
    {
        mTimer = lv_timer_create(Timer, sec * 1000,  NULL);
        lv_timer_set_repeat_count(mTimer, 1); // 计时器仅重复1次，后会自动被删除
        lv_label_set_text(mLable, str);
    }
    else if(mStatus == MSG_BOX_ST_TIMER_SHOW)   // 更改MSGBOX显示内容和显示时间
    {
        lv_timer_reset(mTimer);
        lv_timer_set_period(mTimer, sec * 1000);
        lv_label_set_text(mLable, str);
    }
    mStatus = MSG_BOX_ST_TIMER_SHOW;
}

void MsgBox_Close()
{
    if(mStatus != MSG_BOX_ST_NOT_SHOW)
    {
        lv_obj_del(mMsgBox);
        mStatus = MSG_BOX_ST_NOT_SHOW;
    }
}
